package com.example.meitao.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.meitao.R;
import com.example.meitao.bean.User;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.HashMap;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends AppCompatActivity{
    //获取昵称电话号
    private EditText et_number;
    private EditText et_security;
    private String number;
    private ProgressDialog dialog;
    //获取密码
    private EditText et_registpwd;
    //注册按钮
   private Button bt_regist;
    //获取电话号和密码
    private String number1;
    private String pwd;

    //初始化数据库
    private DbManager mDb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        SMSSDK.initSDK(this, "16331faec3df4", "0fcd330a88ccd71b05d3e05575348ae7");
        initView();
        initData();
        setListener();
        SMSSDK.registerEventHandler(ev);
        DbManager.DaoConfig config =new DbManager.DaoConfig();
       //获取数据库操作对象
        mDb = x.getDb(config);
    }

    private void initData() {

    }

    private void setListener() {
        bt_regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                number1 = et_number.getText().toString();
                pwd = et_registpwd.getText().toString();
                //将电话号和密码添加到数据库
                if(!TextUtils.isEmpty(number1)&&!TextUtils.isEmpty(pwd)) {
                    User user = new User();
                    user.setName(number1);
                    user.setPwd(pwd);
                    //保存到数据库
                    try {
                        mDb.save(user);
                        Log.d("TAG", "onClick:-----mDb"+user.getName()+":密码:"+user.getPwd());
                        Toast.makeText(RegisterActivity.this, "注册成功!", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(RegisterActivity.this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
                }
                /*if(!TextUtils.isEmpty(number1)&&!TextUtils.isEmpty(pwd)){
                    Intent intent =new Intent(RegisterActivity.this,LoginActivity.class);
                    //传电话号和密码
                    intent.putExtra("number1",number1);
                    intent.putExtra("pwd",pwd);
                    Log.d("TAG", "onClick: ----------number1"+number1);
                    Log.d("TAG", "onClick: ----------pwd"+pwd);
                    startActivity(intent);

                }else{
                    Toast.makeText(RegisterActivity.this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
                }*/

            }
        });
    }

    private void initView() {
        getSupportActionBar().hide();
        et_number = (EditText) findViewById(R.id.et_register_phone);
        et_security = (EditText) findViewById(R.id.et_register_verify);
        et_registpwd = (EditText) findViewById(R.id.et_register_pwd);
        bt_regist = (Button) findViewById(R.id.bt_register_register);
    }


    public void onClick(View view) {
        if (view != null) {
            switch (view.getId()) {
                case R.id.bt_register_register:
                    //注册监听

                    break;
                case R.id.iv_register_chose:
                    finish();
                    break;
                default:
                    break;
            }
        }
    }
    /**
     * 短信验证的回调监听
     */
    private EventHandler ev = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) { //回调完成
                //提交验证码成功,如果验证成功会在data里返回数据。data数据类型为HashMap<number,code>
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Log.e("TAG", "提交验证码成功" + data.toString());
                    HashMap<String, Object> mData = (HashMap<String, Object>) data;
                    String country = (String) mData.get("country");//返回的国家编号
                    String phone = (String) mData.get("phone");//返回用户注册的手机号

                    Log.e("TAG", country + "====" + phone);

                    if (phone.equals(number)) {
                        runOnUiThread(new Runnable() {//更改ui的操作要放在主线程，实际可以发送hander
                            @Override
                            public void run() {
                                showDailog("恭喜你！通过验证");
                                dialog.dismiss();
                                //    Toast.makeText(MainActivity.this, "通过验证", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showDailog("验证失败");
                                dialog.dismiss();
                                //     Toast.makeText(MainActivity.this, "验证失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功
                    Log.e("TAG", "获取验证码成功");
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表

                }
            } else {
                ((Throwable) data).printStackTrace();
            }
        }
    };

    private void showDailog(String text) {
        new AlertDialog.Builder(this)
                .setTitle(text)
                .setPositiveButton("确定", null)
                .show();
    }

    /**
     * 获取验证码
     *
     * @param v
     */
    public void getSecurity(View v) {
        number = et_number.getText().toString().trim();
        //发送短信，传入国家号和电话---使用SMSSDK核心类之前一定要在MyApplication中初始化，否侧不能使用
        if (TextUtils.isEmpty(number)) {
            Toast.makeText(this, "号码不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            SMSSDK.getVerificationCode("+86", number);
            Toast.makeText(this, "发送成功:" + number, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 向服务器提交验证码，在监听回调中判断是否通过验证
     *
     * @param v
     */
    public void testSecurity(View v) {
        String security = et_security.getText().toString();
        if (!TextUtils.isEmpty(security)) {
            dialog = ProgressDialog.show(this, null, "正在验证...", false, true);
            //提交短信验证码
            SMSSDK.submitVerificationCode("+86", number, security);//国家号，手机号码，验证码
            Toast.makeText(this, "提交了注册信息:" + number, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //要在activity销毁时反注册，否侧会造成内存泄漏问题
        SMSSDK.unregisterAllEventHandler();
    }
}
